<template>
  <q-form @submit="submit" class="q-gutter-md dialog-content" ref="myForm">
    <div :style="{height: isCompete? '576px': '515px'}" style="overflow-y: auto" class="scrollbar">
      <div class="detail-container flex">
        <div class="margin-r-20">网关序列号: {{ driverParams.gatewaySN || '-' }}</div>
        <div class="margin-r-20">网关型号: {{ driverParams.productName || '-' }}</div>
      </div>
      <q-separator />
      <div>

      </div>
      <div class="gateway-container">
        <div class="left">
          <div style="padding-left: 26px">
            <yz-input v-model="wanParams.netPortConf"
                      :rules="[0]"
                      width="100px"
                      style="width: 276px"
                      inputType="select"
                      :options="wanOptions"
                      title="WAN口配置"/>
            <yz-input v-model="wanParams.dns2"
                      width="100px"
                      style="width: 276px"
                      inputType="input"
                      title="DNS2"/>
          </div>
          <div class="title" v-if="isMobile">
            Mobile配置
          </div>
          <div style="padding-left: 26px" v-if="isMobile">
            <q-toggle
              v-model="wanParams.watchDog"
              label="自动复位"
              left-label
              :true-value="1"
              :false-value="0"
              style="padding-left: 32px;padding-bottom: 12px"
            />
            <yz-input v-model="wanParams.apn"
                      style="width: 276px"
                      inputType="input"
                      title="APN"/>
            <yz-input v-model="wanParams.password"
                      style="width: 276px"
                      inputType="input"
                      title="密码"/>
          </div>
          <div class="title">
            LAN1配置
          </div>
          <div style="padding-left: 26px">
            <div>
              <div style="display: flex;align-items: center">
                <label class="text-right name mode-type bold">分配模式:</label>
                <div style="margin-bottom: 20px">
                  <CustomizedSwitch :disabled="wanType === 'lan'" style="width: 110px" :options="modeOption" v-model="formData.dhcp"/>
                </div>
              </div>

              <q-input style="width: 266px" v-model.trim="formData.ipaddr" outlined dense :disable="formData.dhcp === 1 || wanType === 'lan'"
                       :rules="[val => formData.dhcp === 1 || (val && val.length > 0) || '请填写ip地址',
                       val => formData.dhcp === 1 || (val && /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(val)) || '请输入合法ip地址']">
                <template v-slot:before>
                  <label class="text-right name label-width bold"><span class="text-red" v-if="formData.dhcp !== 1">*</span>IP地址:</label>
                </template>
              </q-input>

              <q-input style="width: 266px" v-model.trim="formData.netmask" outlined dense :disable="formData.dhcp === 1 || wanType === 'lan'"
                       :rules="[val => formData.dhcp === 1 || (val && val.length > 0) || '请填写子网掩码',
                       val => formData.dhcp === 1 || (val && /^(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(?:\.(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/.test(val)) || '请输入合法子网掩码']">
                <template v-slot:before>
                  <label class="text-right name bold"><span class="text-red" v-if="formData.dhcp !== 1">*</span>子网掩码:</label>
                </template>
              </q-input>

              <q-input style="width: 266px" v-model.trim="formData.gateway" outlined dense :disable="formData.dhcp === 1 || wanType === 'lan'"
                       :rules="[val => formData.dhcp === 1 || (val && val.length > 0) || '请填写网关地址',
                       val => formData.dhcp === 1 || (val && /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(val)) || '请输入合法ip地址']">
                <template v-slot:before>
                  <label class="text-right name bold"><span class="text-red" v-if="formData.dhcp !== 1">*</span>网关地址:</label>
                </template>
              </q-input>

              <div class="title">网卡速率</div>

              <q-select
                style="width: 266px"
                outlined
                dense
                emit-value
                map-options
                options-dense
                :disable="wanType === 'lan'"
                :rules="[ val => val !== '' || ' 请选择网卡速率']"
                :options="speedOptions"
                v-model="formData.speed">
                <template v-slot:no-option>
                  <div class="no-option" />
                </template>
                <template v-slot:before>
                  <label class="text-right name bold"><span class="text-red">*</span>网速模式:</label>
                </template>
              </q-select>
            </div>
          </div>
        </div>
        <div class="left">
          <div style="padding-left: 26px">
            <yz-input v-model="wanParams.dns1"
                      width="82px"
                      style="width: 266px"
                      inputType="input"
                      :rules="(wanParams.netPortConf === 'lan_0' || wanParams.netPortConf  === 'lan_1') ? [0] : []"
                      title="DNS1"/>
          </div>
          <div style="margin-top: 88px;padding-left: 26px" v-if="isMobile">
            <yz-input v-model="wanParams.mode"
                      width="82px"
                      style="width: 266px"
                      inputType="select"
                      :options="modeOptions"
                      :rules="[0]"
                      title="拨号方式"/>
            <yz-input v-model="wanParams.user"
                      width="82px"
                      style="width: 266px"
                      inputType="input"
                      title="用户名"/>
          </div>
          <div class="title" style="margin-top: 50px">
            LAN2配置
          </div>
          <div style="padding-left: 26px">
            <div>
              <div style="display: flex;align-items: center">
                <label class="text-right name mode-type bold">分配模式:</label>
                <div style="margin-bottom: 20px">
                  <CustomizedSwitch style="width: 110px" :options="modeOption" v-model="formData2.dhcp"/>
                </div>
              </div>

              <q-input style="width: 266px" v-model.trim="formData2.ipaddr" outlined dense :disable="formData2.dhcp === 1"
                       :rules="[val => formData2.dhcp === 1 || (val && val.length > 0) || '请填写ip地址',
                       val => formData2.dhcp === 1 || (val && /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(val)) || '请输入合法ip地址']">
                <template v-slot:before>
                  <label class="text-right name label-width bold"><span class="text-red" v-if="formData2.dhcp !== 1">*</span>IP地址:</label>
                </template>
              </q-input>

              <q-input style="width: 266px" v-model.trim="formData2.netmask" outlined dense :disable="formData2.dhcp === 1"
                       :rules="[val => formData2.dhcp === 1 || (val && val.length > 0) || '请填写子网掩码',
                       val => formData2.dhcp === 1 || (val && /^(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(?:\.(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/.test(val)) || '请输入合法子网掩码']">
                <template v-slot:before>
                  <label class="text-right name bold"><span class="text-red" v-if="formData2.dhcp !== 1">*</span>子网掩码:</label>
                </template>
              </q-input>

              <q-input style="width: 266px" v-model.trim="formData2.gateway" outlined dense :disable="formData2.dhcp === 1"
                       :rules="[val => formData2.dhcp === 1 || (val && val.length > 0) || '请填写网关地址',
                       val => formData2.dhcp === 1 || (val && /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(val)) || '请输入合法ip地址']">
                <template v-slot:before>
                  <label class="text-right name bold"><span class="text-red" v-if="formData2.dhcp !== 1">*</span>网关地址:</label>
                </template>
              </q-input>

              <div class="title">网卡速率</div>

              <q-select
                style="width: 266px"
                outlined
                dense
                emit-value
                map-options
                options-dense
                :options="speedOptions"
                :rules="[ val => val !== '' || ' 请选择网卡速率']"
                v-model="formData2.speed">
                <template v-slot:no-option>
                  <div class="no-option" />
                </template>
                <template v-slot:before>
                  <label class="text-right name bold"><span class="text-red">*</span>网速模式:</label>
                </template>
              </q-select>
            </div>
          </div>
        </div>
      </div>
    </div>
    <q-separator />
    <div class="dialog-footer text-center margin-t-10">
      <q-btn outline label="取消" color="primary" @click="$emit('hideDialog')" class="q-mr-md"/>
      <q-btn unelevated label="完成" color="primary" type="submit" :loading="submitting"/>
      <span v-if="!isCompete" style="color: #999999;cursor: pointer" class="margin-l-20" @click="skipBind">跳过</span>
    </div>
  </q-form>
</template>

<script>
import CustomizedSwitch from 'src/components/customized-switch'
import { updatePlcLan } from '../../../../../boot/miot/plc-list'
import { Dialog } from 'quasar'
import { mapGetters } from 'vuex'
import { modeOptions, wanOptions } from './constant'

export default {
  name: 'config-gateway',
  components: {
    CustomizedSwitch
  },
  props: {
    moduleType: {
      type: Number,
      default: 0
    },
    isCompete: {
      type: Boolean,
      default: false
    },
    driverParams: {
      type: Object,
      default: () => ({
        gatewaySN: '',
        productName: '',
        ucloudBoxNum: ''
      })
    },
    wanType: {
      type: String,
      default: ''
    },
    lanInfo: {
      type: Object,
      default: () => {}
    },
    mobileConf: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      modeOptions: modeOptions,
      wanOptions: wanOptions,
      submitting: false,
      // LAN1配置
      formData: {
        dhcp: 0,
        gateway: '192.168.1.1',
        ipaddr: '192.168.1.10',
        netmask: '255.255.255.0',
        speed: 4
      },
      formDataTemp: {},
      // LAN2配置
      formData2: {
        dhcp: 0,
        gateway: '192.168.2.1',
        ipaddr: '192.168.2.10',
        netmask: '255.255.255.0',
        speed: 4
      },
      wanParams: {
        netPortConf: null,
        dns1: '',
        dns2: '',
        watchDog: 1,
        apn: 'apn',
        mode: 'SYS',
        user: 'user',
        password: 'password'
      },
      formData2Temp: {},
      modeOption: [
        {
          value: 1,
          label: 'DHCP'
        },
        {
          value: 0,
          label: '静态'
        }
      ],
      speedOptions: [
        {
          value: 0,
          label: '自动'
        },
        {
          value: 1,
          label: '10M半双工'
        },
        {
          value: 2,
          label: '10M全双工'
        },
        {
          value: 3,
          label: '100M半双工'
        },
        {
          value: 4,
          label: '100M全双工'
        }
      ]
    }
  },
  watch: {
    lanInfo: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val?.lan0) {
          if (val.lan0.dhcp !== null) {
            this.formData.dhcp = val.lan0.dhcp
          }
          if (val.lan0.gateway) {
            this.formData.gateway = val.lan0.gateway
          }
          if (val.lan0.ipaddr) {
            this.formData.ipaddr = val.lan0.ipaddr
          }
          if (val.lan0.netmask) {
            this.formData.netmask = val.lan0.netmask
          }
          if (val.lan0.speed !== undefined) {
            this.formData.speed = val.lan0.speed
          }
        }
        if (val?.lan1) {
          if (val.lan1.dhcp !== null) {
            this.formData2.dhcp = val.lan1.dhcp
          }
          if (val.lan1.gateway) {
            this.formData2.gateway = val.lan1.gateway
          }
          if (val.lan1.ipaddr) {
            this.formData2.ipaddr = val.lan1.ipaddr
          }
          if (val.lan1.netmask) {
            this.formData2.netmask = val.lan1.netmask
          }
          if (val.lan1.speed !== undefined) {
            this.formData2.speed = val.lan1.speed
          }
        }
      }
    },
    mobileConf: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val) {
          if (val.mobileApn) {
            this.wanParams.apn = val.mobileApn
          }
          if (val.mobileMode) {
            this.wanParams.mode = val.mobileMode
          }
          if (val.mobileUser) {
            this.wanParams.user = val.mobileUser
          }
          if (val.mobilePassword) {
            this.wanParams.password = val.mobilePassword
          }
          if (val.netPortConf) {
            this.wanParams.netPortConf = val.netPortConf
          }
          if (val.watchDog !== undefined) {
            this.wanParams.watchDog = val.watchDog
          } else {
            this.wanParams.watchDog = 1
          }
          this.wanParams.dns1 = val.dns ? val.dns[0] : ''
          this.wanParams.dns2 = val.dns ? val.dns[1] : ''
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ]),
    isMobile () {
      return this.wanParams.netPortConf === 'mobile'
    }
  },
  methods: {
    async submit () {
      this.submitting = true
      const dns = []
      if (this.wanParams.dns1) dns.push(this.wanParams.dns1)
      if (this.wanParams.dns2) dns.push(this.wanParams.dns2)
      const params = {
        dns,
        lan0: this.formData,
        lan1: this.formData2,
        mobileApn: this.wanParams.apn,
        mobileMode: this.wanParams.mode,
        mobilePassword: this.wanParams.password,
        mobileUser: this.wanParams.user,
        moduleType: this.moduleType,
        netPortConf: this.wanParams.netPortConf,
        productId: this.driverParams.productId,
        ucloudBoxNum: this.driverParams.ucloudBoxNum,
        watchDog: this.wanParams.watchDog,
        gatewayId: this.driverParams.gatewayId
      }
      try {
        const res = await updatePlcLan(params)
        if (res.code === '1200') {
          // this.$q.loading.show({
          //   message: '网关初始化需要几分钟，请耐心等待'
          // })
          // await this.checkOnline()
          this.$emit('successSubmit')
        } else {
          this.$message.warning('配置失败')
        }
      } catch (e) {
      } finally {
        this.$q.loading.hide()
        this.submitting = false
      }
    },

    skipBind () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要跳过此步骤吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        this.$emit('bindNone')
      })
    },

    /**
     * 检查盒子是否在线
     */
    checkOnline () {
      return new Promise((resolve, reject) => {
        if (this.client && this.client.connected) {
          const subscribe = this.client.subscribe(
            `/topic/deploy/newBox/${this.driverParams.ucloudBoxNum}`,
            (message) => {
              try {
                subscribe.unsubscribe()
                const ret = JSON.parse(message.body)
                if (ret && ret.data && ret.data.status === 'success') {
                  resolve()
                } else {
                  Dialog.create({
                    title: `<p class="dialog-notice-title">
                <i class="iconfont icontubiao-28" ></i>部署失败,请重试</p>`,
                    html: true,
                    ok: {
                      unelevated: true,
                      label: '确认'
                    }
                  })
                  reject()
                }
              } catch (e) {
                console.log('解析socket内存报警错误' + e)
                reject()
              }
            }
          )
        } else {
          Dialog.create({
            title: `<p class="dialog-notice-title">
                <i class="iconfont icontubiao-28" ></i>websocket断开连接啦~请稍后重试</p>`,
            html: true,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
          reject()
        }
      })
    }
  }
}
</script>

<style scoped lang="stylus">
/deep/ .q-toggle__label{
  font-size: 16px;
  color: #333;
}
.detail-container{
  padding: 20px;
  font-size: 14px;
  line-height: 1;
}
.gateway-container
  padding 19px
  display flex
  .mode-type
    line-height 1
    margin-right 6px
    margin-bottom 20px
  .bold
    font-weight 500
  .left
  .right
    width 50%
    .title
      line-height 1
      font-size 16px
      margin-bottom 20px
      color $primary
</style>
